package com.xm.xmds1705083.service.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.xm.xm.config.MsgConfig;
import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.*;
import com.xm.xmds1705083.service.dto.DuoduoUserDto;
import com.xm.xmds1705083.service.dto.TokenModel;
import com.xm.xmds1705083.service.mapper.DuoduoSmsMapper;
import com.xm.xmds1705083.service.mapper.DuoduoUserMapper;
import com.xm.xmds1705083.service.mapper.DuoduoUserSpaceMapper;
import com.xm.xmds1705083.service.model.DuoduoSms;
import com.xm.xmds1705083.service.model.DuoduoUser;
import com.xm.xmds1705083.service.model.DuoduoUserSpace;
import com.xm.xmds1705083.service.model.SocketEntity;
import com.xm.xmds1705083.service.service.DuoduoUserService;
import com.xm.xmds1705083.service.service.TokenManager;
import com.xm.xmds1705083.service.util.GlobalError;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 杭州新苗网络科技有限公司
 * @author meihf
 * @date 2017/06/14
 * @description
*/ 
@Service("duoduoUserService")
public class DuoduoUserServiceImpl extends ServiceImpl<DuoduoUserMapper,DuoduoUser> implements DuoduoUserService {

    @Autowired
    DuoduoUserMapper duoduoUserMapper;

    @Autowired
    TokenManager tokenManager;

    @Autowired
    DuoduoSmsMapper duoduoSmsMapper;

    @Autowired
    DuoduoUserSpaceMapper duoduoUserSpaceMapper;

    @Override
    public ResultDto login(SearchDto searchDto) {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        try {
             if (!filed.has("loginName") || !filed.has("password")){
                  resultDto.setMsg(ErrorCode.E10011);
                  resultDto.setCode(ErrorCode.C10011);
                  return resultDto;
              }
            long loginName = filed.getLong("loginName");
            String password = filed.getString("password");
            if (!ValidateUtils.isMobileNO(loginName)){
                resultDto.setMsg(ErrorCode.E10004);
                resultDto.setCode(ErrorCode.C10004);
                return resultDto;
            }else if (Strings.isNullOrEmpty(password)){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            } else {
                EntityWrapper entityWrapper = new EntityWrapper();
                entityWrapper.where(" phone={0} and status=0 ",loginName);
                List<DuoduoUser> duoduoUserList = duoduoUserMapper.selectList(entityWrapper);
                if (duoduoUserList.size()==0){
                    resultDto.setCode(ErrorCode.C10009);
                    resultDto.setMsg(ErrorCode.E10009);
                    return resultDto;
                }else {
                    DuoduoUser duoduoUser = duoduoUserList.get(0);
                    if (!DigestUtils.md5Hex(password).equals(duoduoUser.getPassword())){
                        resultDto.setCode(ErrorCode.C10002);
                        resultDto.setMsg(ErrorCode.E10002);
                        return resultDto;
                    }
                    TokenModel tokenModel = tokenManager.createToken(duoduoUser.getId(), String.valueOf(UUID.randomUUID()),duoduoUser.getPhone());
                    DuoduoUserDto duoduoUserDto = BeanUtils.copy(duoduoUser,DuoduoUserDto.class);
                    duoduoUserDto.setToken(tokenModel.getToken());
                    resultDto.setData(duoduoUserDto);
                    resultDto.setMsg("登录成功");
                }
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }finally {
            lock.unlock();
        }
        return resultDto;
    }

    @Override
    public ResultDto register(SearchDto searchDto) {
        ReentrantLock reentrantLock = new ReentrantLock();
        reentrantLock.lock();
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
           //先检测验证码是否正确
             ResultDto duoduoSmsResult = checkSMS(searchDto);
             if (duoduoSmsResult.getCode()!=0){
                 return duoduoSmsResult;
             }else {
                 //校验成功保存到库里 先检测是否已经注册
                 EntityWrapper entityWrapper = new EntityWrapper();
                 entityWrapper.where(" phone={0} and status=0 ",filed.getLong("phone"));
                 int count = duoduoUserMapper.selectCount(entityWrapper);
                 if (ValidateUtils.isGreaterThan0(count)){
                     resultDto.setMsg(ErrorCode.E10008);
                     resultDto.setCode(ErrorCode.C10008);
                     return resultDto;
                 }else {
                     //验证密码
                     String password = filed.getString("password");
                     if(Strings.isNullOrEmpty(password)){
                         resultDto.setCode(ErrorCode.C10010);
                         resultDto.setMsg(ErrorCode.E10010);
                         return resultDto;
                     }
                     filed.remove("validateCode");
                     String passwordMd5 = DigestUtils.md5Hex(password);
                     filed.put("password",passwordMd5);
                     filed.put("createTime",searchDto.getTime());
                     //vip 以及 status 默认为0
                     DuoduoUser duoduoUser = (DuoduoUser) JSONObject.toBean(filed,DuoduoUser.class);
                     int result = duoduoUserMapper.insert(duoduoUser);
                     if (ValidateUtils.isGreaterThan0(result)){
                         resultDto.setMsg("注册成功");
                         EntityWrapper entityWrapper1 = new EntityWrapper();
                         entityWrapper1.where(" phone={0} and status=0 ",filed.getLong("phone"));
                         DuoduoUser duoduoUser1 = (DuoduoUser) duoduoUserMapper.selectList(entityWrapper1).get(0);
                         //自动生成三条
                         DuoduoUserSpace duoduoUserSpace = new DuoduoUserSpace();
                         duoduoUserSpace.setIsAuth(0);
                         duoduoUserSpace.setAddress("中山北路52");
                         duoduoUserSpace.setArea("330100");
                         duoduoUserSpace.setBillRule((float) 5.0);
                         duoduoUserSpace.setUserId(duoduoUser1.getId());
                         duoduoUserSpace.setProvince("330000");
                         duoduoUserSpace.setCounty("330104");
                         String i = "A,B,C,D,E";
                         int random = (int) (Math.random()*3);
                         String num = i.split(",")[random];
                         for (int ii=0;ii<3;ii++) {
                             duoduoUserSpace.setParkingSpace(num+String.valueOf(((int)Math.random()*20)));
                             duoduoUserSpaceMapper.insert(duoduoUserSpace);
                         }
                     }else {
                         resultDto.setMsg(ErrorCode.E11003);
                         resultDto.setCode(ErrorCode.C11003);
                     }
                 }
             }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }finally {
            reentrantLock.unlock();
        }
        return resultDto;
    }

    @Override
    public ResultDto updatePassword(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            //验证验证码是否正确
            ResultDto result = checkSMS(searchDto);
            if (result.getCode()!=0){
                return result;
            }
            String newPassword = filed.getString("password");
            if (Strings.isNullOrEmpty(newPassword)){
                resultDto.setCode(ErrorCode.C10010);
                resultDto.setMsg(ErrorCode.E10010);
                return resultDto;
            }
            //检查用户是否存在
            List<DuoduoUser> duoduoUserList = duoduoUserMapper.selectList(new EntityWrapper<DuoduoUser>().
                    where(" phone={0} and status=0 ", filed.getLong("phone")));
            if (duoduoUserList.size()==0){
                resultDto.setCode(ErrorCode.C10009);
                resultDto.setMsg(ErrorCode.E10009);
                return resultDto;
            }else {
                //修改密码
                DuoduoUser duoduoUser = duoduoUserList.get(0);
                duoduoUser.setPassword(DigestUtils.md5Hex(newPassword));
                int updateResult = duoduoUserMapper.updateById(duoduoUser);
                if (ValidateUtils.isGreaterThan0(updateResult)){
                    resultDto.setMsg("密码修改成功");
                }else {
                    resultDto.setMsg(ErrorCode.E11003);
                    resultDto.setCode(ErrorCode.C11003);
                }
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto myCenter(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            long userId = searchDto.getAppUserId();
            DuoduoUser duoduoUser = duoduoUserMapper.selectById(userId);
            if (duoduoUser==null){
                resultDto.setMsg(ErrorCode.E10001);
                resultDto.setCode(ErrorCode.C10001);
            }else {
                resultDto.setData(duoduoUser);
            }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    public ResultDto checkSMS(SearchDto searchDto) {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        try{
            if (!filed.has("phone") || !filed.has("sendtype") || !filed.has("validateCode")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            }
            long phone = filed.getLong("phone");
            int sendtype = filed.getInt("sendtype");
            int validateCode = filed.getInt("validateCode");
            if(!ValidateUtils.isMobileNO(phone)){
                resultDto.setCode(ErrorCode.C10004);
                resultDto.setMsg(ErrorCode.E10004);
                return  resultDto;
            }
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" mobile = {0}  and sendtype = {1}  " , phone,
                    sendtype
            );
            entityWrapper.orderBy("validity",false);
            List<DuoduoSms> messageList = duoduoSmsMapper.selectList(entityWrapper);
            if(messageList.isEmpty()){
                resultDto.setCode(ErrorCode.C10006  );
                resultDto.setMsg(ErrorCode.E10006);
                return  resultDto;
            }

            DuoduoSms sms =  messageList.get(0);
            if( sms.getCheckcode().intValue() != validateCode){
                resultDto.setCode(ErrorCode.C10006  );
                resultDto.setMsg(ErrorCode.E10006);
                return  resultDto;
            }
            if( DateUtils.getTimeSecondLong() > sms.getValidity() ){
                resultDto.setCode(ErrorCode.C10007);
                resultDto.setMsg(ErrorCode.E10007);
                return  resultDto;
            }
            resultDto.setMsg("校验通过");
        }finally {
            lock.unlock();
        }
        return resultDto;
    }

    @Override
    public ResultDto login(SocketEntity entity) {
        ResultDto resultDto = new ResultDto();
        JSONObject param = JSONObject.fromObject(entity.getParam());
        String dataSrc = param.getString("datasrc");
        JSONObject result = new JSONObject();
        if (dataSrc.equals("百胜")){
            String name = param.getString("user");
            String password= param.getString("passwd");
            System.out.print( name+"ppppppppppppppp"+password );
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.where(" phone={0} and password={0} and status=0",name, DigestUtils.md5Hex(password));
            System.out.println(duoduoUserMapper);
            List<DuoduoUser> duoduoUserList = duoduoUserMapper.selectList(entityWrapper);
            if (duoduoUserList.size()==0){
                result.put("result","user not exist");
                result.put("rsv1","");
                result.put("rsv2","");
            }else {
                result.put("result","ok");
                result.put("rsv1","");
                result.put("rsv2","");
            }
        }else {
            result.put("result","数据来源错误");
            result.put("rsv1","");
            result.put("rsv2","");
        }
        resultDto.setData(result.toString());
        return resultDto;
    }

    @Override
    public ResultDto getPaidState(SocketEntity entity) {
        ResultDto resultDto = new ResultDto();
        try {

        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto getPayNotice(SocketEntity entity) {
        ResultDto resultDto = new ResultDto();
        try {
            JSONObject params = JSONObject.fromObject(entity.getParam());
            params.getString("result");
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }


        @Override
        public ResultDto hbToCloud (SocketEntity entity){
            ResultDto resultDto = new ResultDto();
            try {
                JSONObject params = JSONObject.fromObject(entity.getParam());
                String time = params.getString("Time");
                int timeInt = DateUtils.getStringToInt_seconds(time, DateUtils.PATTERN_DATE_TIME_SIMPLE);
                //new 一个json用于封装数据
                JSONObject json = new JSONObject();
                int timeplus = timeInt - DateUtils.getTimeSecondLong().intValue();
                if (timeplus < 30) {
                    json.put("result", "00");
                } else {
                    json.put("result", timeplus);
                }
                resultDto.setData(json);

            } catch (RuntimeException e) {
                e.printStackTrace();
                resultDto.setCode(ErrorCode.C10013);
                resultDto.setMsg(ErrorCode.E10013);
            }
            return resultDto;
        }

    @Override
    public ResultDto addMyselfCertf(SearchDto searchDto) {
        //现在一期认证车位给的是假数据
        ResultDto resultDto = new ResultDto();
        searchDto.setPageNo((searchDto.getPageNo() - 1) * searchDto.getPageSize());
        JSONObject filed = searchDto.getFiled();
        try {
            if (!filed.has("name" )||!filed.has("idCard")){
                resultDto.setMsg(ErrorCode.E10011);
                resultDto.setCode(ErrorCode.C10011);
                return resultDto;
            } else{

                String name= filed.getString("name");
                String idCard=filed.getString("idCard");
                EntityWrapper entityWrapper1 = new EntityWrapper();
                entityWrapper1.where("id={0} and userAuth=1",searchDto.getAppUserId());//searchDto.getAppUserId()
                List<DuoduoUser> lists = duoduoUserMapper.selectList(entityWrapper1);
                if (lists.size()>0) {
                    resultDto.setCode(GlobalError.C11031);
                    resultDto.setMsg(GlobalError.E11031);
                }else {
                    if (Strings.isNullOrEmpty(name) || Strings.isNullOrEmpty(idCard)) {
                        resultDto.setMsg(ErrorCode.E10011);
                        resultDto.setCode(ErrorCode.C10011);
                        return resultDto;
                    } else {
                        DuoduoUser user = new DuoduoUser();
                        user.setIdCard(idCard);
                        user.setName(name);
                        user.setUserAuth(1);
                        EntityWrapper entityWrapper = new EntityWrapper();
                        entityWrapper.where("id={0}",searchDto.getAppUserId());//searchDto.getAppUserId()
                        int resule1 = duoduoUserMapper.update(user, entityWrapper);
                        if (ValidateUtils.isGreaterThan0(resule1)) {
                            resultDto.setMsg("用户认证完成");
                        } else {
                            resultDto.setCode(GlobalError.C11038);
                            resultDto.setMsg(GlobalError.E11038);
                        }
                    }
                }
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }


}

